package com.xl.cloud.netty.nio;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author XiangLiang
 * @Since 2025/1/9 11:35
 * @Description: NIOFileChannel01类 - 写入文件
 */
public class NIOFileChannel01 {
    public static void main(String[] args) throws Exception {
        String str = "Hello world!";

        // 创建一个输出流-> channel
        FileOutputStream fileOutputStream = new FileOutputStream("D:\\file01.txt");

        // 通过fileOutputStream获取对应的fileChannel，这个fileChannel的真实类型是FileChannelImpl
        FileChannel fileChannel = fileOutputStream.getChannel();

        // 创建一个缓冲区ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        // 将str放入byteBuffer中
        byteBuffer.put(str.getBytes());

        // 对byteBuffer进行反转flip
        byteBuffer.flip();

        // 将byteBuffer的数据写入到fileChannel中
        fileChannel.write(byteBuffer);

        fileOutputStream.close();
        fileChannel.close();
    }
}
